Unions is a user-defined data type that enables the storage of different data types in the same memory location. Unlike structures, where each member has its own memory space, members of a union share the same memory space. The size of a union is determined by the size of its largest member. Unions are useful when you need to represent a single memory location that can hold values of different types interchangeably.
You can declare variables of a Union type in the same way you declare variables of basic data types.
A union in C like a shared storage space where you can keep different types of things, but the size of the storage is determined by the largest thing you want to put in there. It's like having a box that can fit a big toy or several smaller toys. No matter what you put in the box, it won't overflow because everything shares the same space. This helps save memory, making it a smart choice when you want to use one storage for different-sized things without wasting any space.
1. The Number union is defined with two members: integerValue and floatValue.
2. A variable num of type union Number is declared.
3. The integerValue member is assigned the value 42 and then displayed.
4. The floatValue member is assigned the value 3.14, and its value is displayed.
This demonstrates how a union allows you to use the same memory space for different types of data interchangeably. In this case, the union is used to store both an integer and a float at different times.
Was this helpful?